package com.mz.ozy.activity.me;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alipay.sdk.app.AuthTask;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.mz.ozy.R;
import com.mz.ozy.base.BaseActivity;
import com.mz.ozy.bean.AccountBean;
import com.mz.ozy.bean.MeBean;
import com.mz.ozy.bean.NewCheckJoinMemberBean;
import com.mz.ozy.bean.NewResponeBean;
import com.mz.ozy.bean.UnreadMsgBean;
import com.mz.ozy.mvp.presenter.LoginPresenter;
import com.mz.ozy.mvp.presenter.MePresenter;
import com.mz.ozy.mvp.view.MeContract;
import com.mz.ozy.utils.AppManager;
import com.mz.ozy.utils.QiNiuManger;
import com.mz.ozy.utils.ToastUtils;
import com.mz.ozy.utils.Utils;
import com.mz.ozy.utils.glideUtils.GlideUtils;
import com.mz.ozy.widget.dialog.BaseDialog;
import com.mz.ozy.widget.dialog.NameEditDialog;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.socks.library.KLog;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareConfig;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.functions.Action1;

public class SettingActivity extends BaseActivity<MeContract.View, MePresenter> implements MeContract.View {
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_nick)
    TextView tvNick;
    @BindView(R.id.iv_userIcon)
    ImageView ivUserIcon;
    @BindView(R.id.tv_rele_type)
    TextView tvReleType;
    @BindView(R.id.tv_bind_wx)
    TextView tvBindWx;
    @BindView(R.id.tv_wx_bind)
    TextView tvWxBind;
    @BindView(R.id.tv_bind_ali)
    TextView tvBindAli;
    @BindView(R.id.tv_ali_bind)
    TextView tvAliBind;
    private boolean isSave = false;
    private String token;
    private NameEditDialog mNameDialog;
    private AccountBean dataItem;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        ButterKnife.bind(this);
        initTitle();
        tvCenterTitle.setText("账号信息");
        rightTextView.setTextSize(13);
        rightTextView.setGravity(Gravity.CENTER);
        rightTextView.setTextColor(getResources().getColor(R.color.c_363636));
        rightTextView.setVisibility(View.VISIBLE);
        rightTextView.setText("个人名片");
        rightTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Intent intent = new Intent(SettingActivity.this, BusinessCardActivity.class);
                intent.putExtra("shiming", dataItem.getShiming());
                startActivity(intent);
            }
        });
        mPresenter.upAccountHeader(this);
        token = getIntent().getStringExtra("token");
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.upAccountHeader(this);
    }

    @OnClick({R.id.rele_wx, R.id.rele_ali, R.id.rele_nick, R.id.rele_relname, R.id.loginpwdView, R.id.payPwdView, R.id.bt_exitLogin, R.id.accountManagerView
            , R.id.payAccountView, R.id.bt_logout,R.id.rele_address, R.id.tjView})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rele_wx:
                if (dataItem.getWxnum() == 0) {
                    onWxAuth(SHARE_MEDIA.WEIXIN);
                } else {
                    showTipDialog(1);
                }
                break;
            case R.id.rele_ali:
                if (dataItem.getZfbnum() == 0) {
                    mPresenter.getAli(this);
                } else {
                    showTipDialog(2);
                }
                break;
            case R.id.rele_nick:
                showNameDialog();
                break;
            case R.id.rele_address:
                AddressActivity.go(SettingActivity.this, 0);
                break;
            case R.id.rele_relname:
                //实名认证
                if (dataItem.getShiming() == 0) {
                    VerifiedActivity.go(this, "", "", dataItem.getShiming());
                } else {
                    VerifiedActivity.go(this, dataItem.getUname(), dataItem.getCardid(), dataItem.getShiming());
                }
                break;
            case R.id.loginpwdView:
                startActivity(new Intent(this, LoginPwdActivity.class));
                break;
            case R.id.payPwdView:
                startActivity(new Intent(this, PayPwdActivity.class));
                break;
            case R.id.tjView:
                RecommendServiceActivity.go(this);
                break;
            case R.id.bt_exitLogin:
                mPresenter.exitLogin(this);
                break;

            case R.id.accountManagerView:
                RxPermissions.getInstance(SettingActivity.this)
                        .request(Manifest.permission.CAMERA)//这里填写所需要的权限
                        .subscribe(new Action1<Boolean>() {
                            @Override
                            public void call(Boolean aBoolean) {
                                if (aBoolean) {//true表示获取权限成功（注意这里在android6.0以下默认为true）
                                    PictureSelector.create(SettingActivity.this)
                                            .openGallery(PictureMimeType.ofImage())
                                            .imageSpanCount(4)
                                            .selectionMode(PictureConfig.SINGLE)
                                            .forResult(PictureConfig.CHOOSE_REQUEST);
                                } else {
                                    Log.i("permissions", Manifest.permission.READ_EXTERNAL_STORAGE + "：" + "获取失败");
                                }
                            }
                        });
                // startActivityForResult(new Intent(this, SwitchRoleActivity.class), 100);

                break;
            case R.id.bt_logout:
//                startActivity(new Intent(this, LogoutActivity.class));
                Intent intent=new Intent(this, LogoutActivity.class);
                intent.putExtra("mphone",tvPhone.getText());
                startActivity(intent);
                break;
            case R.id.payAccountView:

                break;
        }
    }

    private void showTipDialog(int type) {
        String content = "";
        if (type == 1) {
            content = "确定解除微信绑定吗？";
        } else if (type == 2) {
            content = "确定解除支付宝绑定吗？";
        }
        final BaseDialog dialog = new BaseDialog(this, R.layout.dialog_tips, Gravity.CENTER, true);
        dialog.setText(R.id.tv_content, content)
                .setText(R.id.tv_title, "解除绑定")
                .setOnViewClick(R.id.tv_confirm, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //解除绑定
                        mPresenter.onCancelBind(SettingActivity.this, type);
                        dialog.toggleDialog();
                    }
                }).setOnViewClick(R.id.tv_cancel, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.toggleDialog();
            }
        });
        dialog.toggleDialog();
    }

    private static final int SDK_AUTH_FLAG = 2;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    HashMap<String, String> authResult = (HashMap<String, String>) msg.obj;

                    String resultStatus = authResult.get("resultStatus");
                    KLog.e("authResult", authResult.toString());
                    if (TextUtils.equals(resultStatus, "9000")) { //授权成功
                        String result = authResult.get("result");
                        //截取auth_code=之后的字符串
                        String str = result.substring(result.indexOf("auth_code="));
                        //截取&之前的字符串
                        String str2 = str.substring(0, str.indexOf("&"));
                        String auth_code = str2.replace("auth_code=", "");
                        mPresenter.getBIndInfo(SettingActivity.this, LoginPresenter.AUTH_TYPE_ALIPAY + "", auth_code);
                    } else {
                        ToastUtils.showToast("授权失败");
                    }
                    break;
                }

                default:
                    break;
            }
        }
    };

    /************************************* 支付宝授权 *****************************************/
    public void onAliPayAuth(final String authInfo) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造AuthTask 对象
                AuthTask authTask = new AuthTask(SettingActivity.this);
                // 调用授权接口，获取授权结果
                Map<String, String> result = authTask.authV2(authInfo, true);

                Message msg = new Message();
                msg.what = SDK_AUTH_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private void onWxAuth(SHARE_MEDIA share_media) {
        //最新版本微信客户端调用接口后也不再出现授权确认页面，确认在微信客户端切换账号后，
        //再次调用登录接口获取的用户资料变化即可
        UMShareConfig config = new UMShareConfig();
        config.isNeedAuthOnGetUserInfo(true);
        UMShareAPI.get(this).setShareConfig(config);

        UMShareAPI.get(this).getPlatformInfo(this, share_media, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {
                KLog.e("onStart()  微信授权开始");
            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                KLog.e("onComplete() 成功");
                ToastUtils.showToast("授权成功");
                //微信返回的openID和unionID都可以实现用户标识的需求，二者的区别在于，unionID可以实现同一个开发者账号下的应用之间账号打通的需求

                /*unionId = map.get("uid");     //就是unionid，友盟封装了
                wx_nickname = map.get("name");        //名字
                String gender = map.get("gender");    //性别
                wx_useravatar = map.get("iconurl");  //头像
                if ("男".equals(gender)) {
                    wx_sex = "1";
                } else {
                    wx_sex = "0";
                }
               */
                mPresenter.getBIndInfo(SettingActivity.this, LoginPresenter.AUTH_TYPE_WX + "", map.get("unionid"));
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                ToastUtils.showToast(throwable.getMessage());
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {
                ToastUtils.showToast("授权取消");
            }
        });
    }

    private void showNameDialog() {
        try {
            if (mNameDialog == null) {
                mNameDialog = new NameEditDialog(this);
                mNameDialog.setOnDialogListener(name -> {
                    tvNick.setText(name);
                    mPresenter.uploadHeader(SettingActivity.this, "", name);
                });
            }
            mNameDialog.toggleDialog();
        } catch (Exception e) {

        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PictureConfig.CHOOSE_REQUEST && resultCode == RESULT_OK) {
            List<LocalMedia> images = PictureSelector.obtainMultipleResult(data);
            List<String> uploadlist = Utils.convertToImageList(images);
            if (uploadlist != null && uploadlist.size() > 0) {
                uploadAvatar(uploadlist.get(0));
            }
        }
    }


    private void uploadAvatar(final String path) {
        QiNiuManger.getInstance().getUploadManager().put(path, QiNiuManger.getInstance().getKeyName(), token, new UpCompletionHandler() {
            @Override
            public void complete(String key, ResponseInfo info, JSONObject response) {
                if (info.isOK()) {
                    ToastUtils.showToast(R.string.upload_success);
                    mPresenter.uploadHeader(SettingActivity.this, key, "");
                }
            }
        }, null);
    }

    @Override
    public void getgetMeInfoSuccess(MeBean bean) {

    }

    @Override
    public void getAccountSuccess(AccountBean bean) {
        dataItem = bean;
        if (bean.getNickname().equals("")) {
            tvNick.setText("未设置");
        } else {
            tvNick.setText(bean.getNickname());
        }
        if (bean.getShiming() == 0) {
            tvReleType.setText("未实名");
        } else {
            tvReleType.setText("已实名");
        }
        if (bean.getWxnum() == 0) {
            tvBindWx.setText("绑定微信");
            tvWxBind.setText("未绑定");
        } else {
            tvBindWx.setText("解绑微信");
            tvWxBind.setText("已绑定");
        }
        if (bean.getZfbnum() == 0) {
            tvBindAli.setText("绑定支付宝");
            tvAliBind.setText("未绑定");
        } else {
            tvBindAli.setText("解绑支付宝");
            tvAliBind.setText("已绑定");
        }
        ivUserIcon.setTag(bean.getUseravatar());
        GlideUtils.loadAvatar(this, ivUserIcon, bean.getUseravatar());
        //ivUserIcon.setImageURI();
        tvPhone.setText(bean.getUsername());

    }

    @Override
    public void uploadHeaderSuccess(JSONObject bean) {
        mPresenter.upAccountHeader(this);
    }

    @Override
    public void getxySuccess(MeBean bean) {

    }

    @Override
    public void bindInfo(String type, JSONObject bean) {
        ToastUtils.showToast("绑定成功");
        mPresenter.upAccountHeader(this);
    }

    @Override
    public void getAliSuccess(MeBean bean) {
        onAliPayAuth(bean.getSdkUrl());
    }

    @Override
    public void exitLoginSuccess(JSONObject bean) {
        AppManager.getAppManager().exitLoginActivity(this);
    }


    @Override
    public void onCancelBindSuccess() {
        ToastUtils.showToast("解除绑定成功");
        mPresenter.upAccountHeader(this);
    }

    @Override
    public void getUnreadMsgSuccess(UnreadMsgBean bean) {

    }

}
